<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\ChinaArea
 *
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $parent_id
 * @property string $code
 * @property string $name
 * @property string|null $sulg Url 简称
 * @property int $level 层级
 * @property string $parent_code 父级 code
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereParentCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereParentId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|ChinaArea whereSulg($value)
 */
class ChinaArea extends Model
{
    use HasDateTimeFormatter;

    protected $table = 'china_area';

    public static function getArea($code = 0){
        $list = self::query()->select(['code as value','name as text'])->where("parent_code",$code)->get()->toArray();
        if ($list){
            foreach ($list as $key=>$item){
                $children = self::getArea($item['value']);
                if ($children){
                    $list[$key]['children'] = $children;
                }
            }
        }
        return $list;
    }

    public static function getCitys(){
        $list = self::query()->select(['code as value','name'])->where("parent_code",0)->get()->toArray();
        if ($list){
            foreach ($list as $key=>$item){
                $list[$key]['id'] = $item['value'];
                unset($list[$key]['value']);
                $children = self::query()->select(['code as value','name'])->where("parent_code",$item['value'])->get()->toArray();
                if ($children){
                    foreach ($children as $k=>$child){
                        $children[$k]['id'] = $child['value'];
                        unset($children[$k]['value']);
                    }
                    $list[$key]['children'] = $children;
                }
            }
        }
        return $list;
    }
}
